
package com.xtsoft.platform.base.system.service.impl;
/*
*    上海信拓信息技术有限公司 Koala企业综合信息管理系统
*    Copyright (C) 2010-2015 ShangHai XinTuo Software Inc.
*/


import com.xtsoft.core.service.impl.GenericServiceImpl;
import com.xtsoft.platform.base.system.domain.DashboardRole;
import com.xtsoft.platform.base.system.domain.SysDashboard;
import com.xtsoft.platform.base.system.domain.SysRole;
import com.xtsoft.platform.base.system.repository.SysDashboardRepository;
import com.xtsoft.platform.base.system.repository.SysRoleRepository;
import com.xtsoft.platform.base.system.service.SysDashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service("sysDashboardService")
public class SysDashboardServiceImpl extends GenericServiceImpl<SysDashboard,String, SysDashboardRepository> implements SysDashboardService {

	@Autowired
	public SysDashboardRepository sysDashboardRepository;
	@Autowired
	public SysRoleRepository sysRoleRepository;
	

	@Override
	public String getDashboardTree(String roleId) {
		List<SysDashboard> dashboardList = sysDashboardRepository.findAll();
		StringBuffer jsonTreeBuffer = new StringBuffer("[");
		String jsonTree = "";
		SysRole sysRole = sysRoleRepository.get(roleId);
		if (null != sysRole) {
			List<SysDashboard> dashborads = new ArrayList();
			if(!sysRole.getDashboardRoles().isEmpty()) {
				dashborads = sysRole.getDashboardRoles().stream().map(action->action.getSysDashboard()).collect(Collectors.toList());
			}
			//List<SysDashboard> dashboradRole = sysRole.getDashboardRoles();
			boolean check = false;
			for (SysDashboard sysDashboard : dashboardList) {
				if (dashborads.contains(sysDashboard)) {
					check = true;
				}
				jsonTreeBuffer.append("{\"id\":\"" + sysDashboard.getDashboardId() + "\",\"text\":\""
						+ sysDashboard.getName() + "\",\"iconCls\":\"x-fa fa-pie-chart\",\"checked\":" + check
						+ ",\"leaf\":true,\"children\":[]},");
				check = false;
			}
			jsonTree = jsonTreeBuffer.substring(0, jsonTreeBuffer.length() - 1) + "]";
		}
		return jsonTree;
	}


	@Override
	public List<SysDashboard> findByRole(String rolealias) {
		List<SysRole> sysRoles = sysRoleRepository.findByAlias(rolealias);
		List<DashboardRole> dashboardRoles = new ArrayList();
		for(SysRole role : sysRoles) {
			dashboardRoles.addAll(role.getDashboardRoles());
		}
		List<SysDashboard> result = new ArrayList();
		result.addAll(dashboardRoles.stream().map(action->action.getSysDashboard()).distinct().collect(Collectors.toList()));
		result = result.stream().sorted(Comparator.comparing(SysDashboard::getSort)).collect(Collectors.toList());
		 
          
		return result;
	}


	

}